package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 陈辉
 * @data 2023 10:02
 * 网关：全局微服务登录验证!
 */
@Component
public class TokenFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 先拿到本次请求的uri路径
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();       //uri: "/api/v1/login/login_auth"

        //2. 根据路径判断是否为登录请求
        if (path.contains("login")){
            //3. 是登录相关：直接放行
            return chain.filter(exchange);
        }

        //4. 不是登录：判断是否有token
        String token = request.getHeaders().getFirst("token");

        //5. 没有token： 返回401,流程结束
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6. 有token: 校验token是否有效
        //6.1 有没有被篡改？有没有过期？
        try {
            Claims body = AppJwtUtil.getClaimsBody(token);
            int res = AppJwtUtil.verifyToken(body);
            //7. 校验失败： 返回401，流程结束
            if (res == 1 || res == 2){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //解析出用户id
            Object userId = body.get("id");
            //往下游微服务路由，追加请求头：userId = id值
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId.toString());
            }).build();
            //重置header
            exchange.mutate().request(serverHttpRequest).build();


        } catch (Exception e) {
            //防止token被篡改
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //8. 校验成功： 放行
        return chain.filter(exchange);
    }
}
